package cn.edu.ctbu.lddweb.webapi;
import cn.edu.ctbu.lddweb.core.PageUtils;
import cn.edu.ctbu.lddweb.pojo.Student;
import cn.edu.ctbu.lddweb.service.StudentService;
import cn.edu.ctbu.lddweb.utils.RUtil;
import cn.edu.ctbu.lddweb.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@Slf4j
@RequestMapping("/webapi/student")
public class TeacherRestController {
    @Autowired
    private StudentService studentService;

    @GetMapping("/list")
    public R<Page<Student>> getAll(int pageIndex,int pageSize){
        Sort sort=Sort.by(Sort.Direction.ASC,"id");
        Pageable pageable=PageRequest.of(pageIndex,pageSize,sort);
        return RUtil.success(studentService.findAll(pageable));
    }

    /**
     * 分页，读取全部内容
     */
    @GetMapping("/getbypage")
    public PageUtils getByPage(@RequestParam(value="page",defaultValue = "0")Integer page,
                               @RequestParam(value = "size",defaultValue = "10")Integer size,
                               @RequestParam(value = "name",defaultValue = "")String name,
                               @RequestParam(value = "searchOpt",defaultValue = "1")String searchOpt)

    {
        Sort sort=Sort.by(Sort.Direction.ASC,"id");
        Page<Student> studentPage;
        Pageable pageable=PageRequest.of(page,size,sort);
        if(StringUtils.isEmpty(name)){
            studentPage=studentService.findAll(pageable);
        }else{
            Student student=new Student();
            ExampleMatcher matcher;
            if(searchOpt.equals("1")){
                //全部模糊查询 即%{name}%
                student.setName(name);
                matcher=ExampleMatcher.matching()
                    .withMatcher("name",ExampleMatcher.GenericPropertyMatcher::contains);
            }else {
                //全部模糊查询 即%{sno}%
                student.setSno(name);
                matcher=ExampleMatcher.matching()
                        .withMatcher("sno",ExampleMatcher.GenericPropertyMatcher::contains);
            }
            Example<Student> example=Example.of(student,matcher);
            studentPage=studentService.findAll(example,pageable);
        }
        PageUtils pageUtils=new PageUtils(studentPage.getContent(),studentPage.getTotalElements());
        return pageUtils;
    }

    @GetMapping("/get/{id}")
    public Student get(@PathVariable Integer id){
        Student student = studentService.findById(id);
        student.setPassword("");
        return student;
    }


    //新增学生 /webapi/student/insert
    @PostMapping("/insert")
    public Student insert(Student student){
        Student student1 = studentService.Insert(student);
        return student1;
    }

    @PostMapping(value = "/add")
    public R add(@Valid Student student, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            String errorMsg=bindingResult.getFieldError().getDefaultMessage();
            log.info(errorMsg);
            return RUtil.error(-10,errorMsg);
        }
        studentService.Insert(student);
        //Integer myid =student.getId();
        return RUtil.success();
    }
    @GetMapping("/validateUser")
    public R validateSnoAndPassword(String sno,String password) throws Exception {
        return  RUtil.success(studentService.validateUsernameAndPassword(sno,password));
    }
    //修改学生 /webapi/student/update
    @PutMapping("/update")
    public Student update(Student student){
        //读取旧数据
        Student oldstudent=studentService.findById(student.getId());
        if(student.getPassword().equals("******")){
            //没有新密码就用旧密码
            student.setPassword(oldstudent.getPassword());
        }
        student=studentService.update(student);
        return student;
    }

    //删除学生 /webapi/student/insert
    @DeleteMapping("/delete/{id}")
    public void  delete(@PathVariable Integer id){
        studentService.delete(id);
    }


}
